Interactive shell




As of PHP 5.1.0, the CLI SAPI provides an interactive shell using the -a option if PHP is compiled with the --with-readline option. As of PHP 7.1.0 the interactive shell is also available on Windows, if the readline extension is enabled. Using the interactive shell you are able to type PHP code and have it executed directly. Executing code using the interactive shell $ php -a Interactive shell php > echo 5+8; 13 php > function addTwo($n) php > { php { return $n + 2; php { } php > var_dump(addtwo(2)); int(4) php > The interactive shell also features tab completion for functions, constants, class names, variables, static method calls and class constants. Tab completion Pressing the tab key twice when there are multiple possible completions will result in a list of these completions: php > strp[TAB][TAB] strpbrk strpos strptime php > strp When there is only one possible completion, pressing tab once will complete the rest on the same line: php > strpt[TAB]ime( Completion will also work for names that have been defined during the current interactive shell session: php > $fooThisIsAReallyLongVariableName = 42; php > $foo[TAB]ThisIsAReallyLongVariableName The interactive shell stores your history which can be accessed using the up and down keys. The history is saved in the ~/.php_history file. As of PHP 5.4.0, the CLI SAPI provides the php.ini settings cli.pager and cli.prompt. The cli.pager setting allows an external program (such as less) to act as a pager for the output instead of being displayed directly on the screen. The cli.prompt setting makes it possible to change the php > prompt. In PHP 5.4.0 it was also made possible to set php.ini settings in the interactive shell using a shorthand notation. Setting php.ini settings in the interactive shell The cli.prompt setting: php > #cli.prompt=hello world :> hello world :> Using backticks it is possible to have PHP code executed in the prompt: php > #cli.prompt=`echo date('H:i:s');` php > 15:49:35 php > echo 'hi'; hi 15:49:43 php > sleep(2); 15:49:45 php > Setting the pager to less: php > #cli.pager=less php > phpinfo(); (output displayed in less) php > The cli.prompt setting supports a few escape sequences: cli.prompt escape sequences
Sequence Description
\e Used for adding colors to the prompt. An example could be \e[032m\v \e[031m\b \e[34m\> \e[0m
\v The PHP version.
\b Indicates which block PHP is in. For instance /* to indicate being inside a multi-line comment. The outer scope is denoted by php.
\> Indicates the prompt character. By default this is >, but changes when the shell is inside an unterminated block or string. Possible characters are: ' " { ( >
Note: Files included through auto_prepend_file and auto_append_file are parsed in this mode but with some restrictions - e.g. functions have to be defined before called.
Note: Autoloading is not available if using PHP in CLI interactive mode.


Built-in web server The web server runs only one single-threaded process, so PHP applications will stall if a request is blocked. Starting the web server $ cd ~/public_html $ php -S localhost:8000 Starting with a specific document root directory $ cd ~/public_html $ php -S localhost:8000 -t foo/ Using a Router Script In this example, requests for images will display them, but requests for HTML files will display "Welcome to PHP": <?php // router.php if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"])) { return false; // serve the requested resource as-is. } else { echo "<p>Welcome to PHP</p>"; } ?> $ php -S localhost:8000 router.php
Example #4 Checking for CLI Web Server Use To reuse a framework router script during development with the CLI web server and later also with a production web server: <?php // router.php if (php_sapi_name() == 'cli-server') { /* route static assets and return false */ } /* go on with normal index.php operations */ ?> $ php -S localhost:8000 router.php Example #5 Handling Unsupported File Types If you need to serve a static resource whose MIME type is not handled by the CLI web server, use: <?php // router.php $path = pathinfo($_SERVER["SCRIPT_FILENAME"]); if ($path["extension"] == "el") { header("Content-Type: text/x-script.elisp"); readfile($_SERVER["SCRIPT_FILENAME"]); } else { return FALSE; } ?> $ php -S localhost:8000 router.php Example #6 Accessing the CLI Web Server From Remote Machines You can make the web server accessible on port 8000 to any interface with: $ php -S 0.0.0.0:8000

Command line options

The list of command line options provided by the PHP binary can be queried at any time by running PHP with the -h switch: Usage: php [options] [-f] <file> [--] [args...] php [options] -r <code> [--] [args...] php [options] [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...] php [options] [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...] php [options] -- [args...] php [options] -a -a Run interactively -c <path>|<file> Look for php.ini file in this directory -n No php.ini file will be used -d foo[=bar] Define INI entry foo with value 'bar' -e Generate extended information for debugger/profiler -f <file> Parse and execute <file>. -h This help -i PHP information -l Syntax check only (lint) -m Show compiled in modules -r <code> Run PHP <code> without using script tags <?..?> -B <begin_code> Run PHP <begin_code> before processing input lines -R <code> Run PHP <code> for every input line -F <file> Parse and execute <file> for every input line -E <end_code> Run PHP <end_code> after processing all input lines -H Hide any passed arguments from external tools. -S <addr>:<port> Run with built-in web server. -t <docroot> Specify document root <docroot> for built-in web server. -s Output HTML syntax highlighted source. -v Version number -w Output source with stripped comments and whitespace. -z <file> Load Zend extension <file>. args... Arguments passed to script. Use -- args when first argument starts with - or script is read from stdin --ini Show configuration file names --rf <name> Show information about function <name>. --rc <name> Show information about class <name>. --re <name> Show information about extension <name>. --rz <name> Show information about Zend extension <name>. --ri <name> Show configuration for extension <name>.
Command line options
Option Long Option Description
-a --interactive Run PHP interactively. For more information, see the Interactive shell section.
-b --bindpath Bind Path for external FASTCGI Server mode (CGI only).
-C --no-chdir Do not chdir to the script's directory (CGI only).
-q --no-header Quiet-mode. Suppress HTTP header output (CGI only).
-T --timing Measure execution time of script repeated count times (CGI only).
-c --php-ini Specifies either a directory in which to look for php.ini, or a custom INI file (which does not need to be named php.ini), e.g.: $ php -c /custom/directory/ my_script.php $ php -c /custom/directory/custom-file.ini my_script.php If this option is not specified, php.ini is searched for in the default locations.
-n --no-php-ini Ignore php.ini completely.
-d --define Set a custom value for any of the configuration directives allowed in php.ini. The syntax is: -d configuration_directive[=value] # Omitting the value part will set the given configuration directive to "1" $ php -d max_execution_time -r '$foo = ini_get("max_execution_time"); var_dump($foo);' string(1) "1" # Passing an empty value part will set the configuration directive to "" php -d max_execution_time= -r '$foo = ini_get("max_execution_time"); var_dump($foo);' string(0) "" # The configuration directive will be set to anything passed after the '=' character $ php -d max_execution_time=20 -r '$foo = ini_get("max_execution_time"); var_dump($foo);' string(2) "20" $ php -d max_execution_time=doesntmakesense -r '$foo = ini_get("max_execution_time"); var_dump($foo);' string(15) "doesntmakesense"
-e --profile-info Activate the extended information mode, to be used by a debugger/profiler.
-f --file Parse and execute the specified file. The -f is optional and may be omitted - providing just the filename to execute is sufficient.
Note: To pass arguments to a script, the first argument must be --, otherwise PHP will interpret them as PHP options.
-h and -? --help and --usage Output a list of command line options with one line descriptions of what they do.
-i --info Calls phpinfo(), and prints out the results. If PHP is not working correctly, it is advisable to use the command php -i and see whether any error messages are printed out before or in place of the information tables. Beware that when using the CGI mode the output is in HTML and therefore very large.
-l --syntax-check Provides a convenient way to perform only a syntax check on the given PHP code. On success, the text No syntax errors detected in <filename> is written to standard output and the shell return code is 0. On failure, the text Errors parsing <filename> in addition to the internal parser error message is written to standard output and the shell return code is set to -1. This option won't find fatal errors (like undefined functions). Use the -f to test for fatal errors too.
Note: This option does not work together with the -r option.
-m --modules Printing built in (and loaded) PHP and Zend modules
$ php -m
[PHP Modules]
xml
tokenizer
standard
session
posix
pcre
overload
mysql
mbstring
ctype

[Zend Modules]
-r --run Allows execution of PHP included directly on the command line. The PHP start and end tags (<?php and ?>) are not needed and will cause a parse error if present.
Note: Care must be taken when using this form of PHP not to collide with command line variable substitution done by the shell. Getting a syntax error when using double quotes $ php -r "$foo = get_defined_constants();" PHP Parse error: syntax error, unexpected '=' in Command line code on line 1 Parse error: syntax error, unexpected '=' in Command line code on line 1 The problem here is that sh/bash performs variable substitution even when using double quotes ". Since the variable $foo is unlikely to be defined, it expands to nothing which results in the code passed to PHP for execution actually reading: $ php -r " = get_defined_constants();" The correct way would be to use single quotes '. Variables in single-quoted strings are not expanded by sh/bash. Using single quotes to prevent the shell's variable substitution $ php -r '$foo = get_defined_constants(); var_dump($foo);' array(370) { ["E_ERROR"]=> int(1) ["E_WARNING"]=> int(2) ["E_PARSE"]=> int(4) ["E_NOTICE"]=> int(8) ["E_CORE_ERROR"]=> [...] If using a shell other than sh/bash, further issues might be experienced - if appropriate, a bug report should be opened at » https://bugs.php.net/. It is still easy to run into trouble when trying to use variables (shell or PHP) in commnad-line code, or using backslashes for escaping, so take great care when doing so. You have been warned!
Note: -r is available in the CLI SAPI, but not in the CGI SAPI.
Note: This option is only intended for very basic code, so some configuration directives (such as auto_prepend_file and auto_append_file) are ignored in this mode.
-B --process-begin PHP code to execute before processing stdin. Added in PHP 5.
-R --process-code PHP code to execute for every input line. Added in PHP 5. There are two special variables available in this mode: $argn and $argi. $argn will contain the line PHP is processing at that moment, while $argi will contain the line number.
-F --process-file PHP file to execute for every input line. Added in PHP 5.
-E --process-end PHP code to execute after processing the input. Added in PHP 5. Using the -B, -R and -E options to count the number of lines of a project. $ find my_proj | php -B '$l=0;' -R '$l += count(@file($argn));' -E 'echo "Total Lines: $l\n";' Total Lines: 37328
-S --server Starts built-in web server. Available as of PHP 5.4.0.
-t --docroot Specifies document root for built-in web server. Available as of PHP 5.4.0.
-s --syntax-highlight and --syntax-highlighting Display colour syntax highlighted source. This option uses the internal mechanism to parse the file and writes an HTML highlighted version of it to standard output. Note that all it does is generate a block of <code> [...] </code> HTML tags, no HTML headers.
Note: This option does not work together with the -r option.
-v --version Using -v to get the SAPI name and the version of PHP and Zend
$ php -v
PHP 5.3.1 (cli) (built: Dec 11 2009 19:55:07)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies
-w --strip Display source with comments and whitespace stripped.
Note: This option does not work together with the -r option.
-z --zend-extension Load Zend extension. If only a filename is given, PHP tries to load this extension from the current default library path on your system (usually /etc/ld.so.conf on Linux systems, for example). Passing a filename with an absolute path will not use the system's library search path. A relative filename including directory information will tell PHP to try loading the extension relative to the current directory.
  --ini Show configuration file names and scanned directories. Available as of PHP 5.2.3. Example #6 --ini example $ php --ini Configuration File (php.ini) Path: /usr/dev/php/5.2/lib Loaded Configuration File: /usr/dev/php/5.2/lib/php.ini Scan for additional .ini files in: (none) Additional .ini files parsed: (none)
--rf --rfunction Show information about the given function or class method (e.g. number and name of the parameters). Available as of PHP 5.1.2. This option is only available if PHP was compiled with Reflection support. Example #7 basic --rf usage $ php --rf var_dump Function [ <internal> public function var_dump ] { - Parameters [2] { Parameter #0 [ <required> $var ] Parameter #1 [ <optional> $... ] } }
--rc --rclass Show information about the given class (list of constants, properties and methods). Available as of PHP 5.1.2. This option is only available if PHP was compiled with Reflection support. Example #8 --rc example $ php --rc Directory Class [ <internal:standard> class Directory ] { - Constants [0] { } - Static properties [0] { } - Static methods [0] { } - Properties [0] { } - Methods [3] { Method [ <internal> public method close ] { } Method [ <internal> public method rewind ] { } Method [ <internal> public method read ] { } } }
--re --rextension Show information about the given extension (list of php.ini options, defined functions, constants and classes). Available as of PHP 5.1.2. This option is only available if PHP was compiled with Reflection support. Example #9 --re example $ php --re json Extension [ <persistent> extension #19 json version 1.2.1 ] { - Functions { Function [ <internal> function json_encode ] { } Function [ <internal> function json_decode ] { } } }
--rz --rzendextension Show the configuration information for the given Zend extension (the same information that is returned by phpinfo()). Available as of PHP 5.4.0.
--ri --rextinfo Show the configuration information for the given extension (the same information that is returned by phpinfo()). Available as of PHP 5.2.2. The core configuration information is available using "main" as extension name. Example #10 --ri example $ php --ri date date date/time support => enabled "Olson" Timezone Database Version => 2009.20 Timezone Database => internal Default timezone => Europe/Oslo Directive => Local Value => Master Value date.timezone => Europe/Oslo => Europe/Oslo date.default_latitude => 59.930972 => 59.930972 date.default_longitude => 10.776699 => 10.776699 date.sunset_zenith => 90.583333 => 90.583333 date.sunrise_zenith => 90.583333 => 90.583333
Note: Options -rBRFEH, --ini and --r[fcezi] are available only in CLI.